// API配置
const API_BASE_URL = window.location.origin + '/api';

// 全局变量
let currentUser = null;
let authToken = localStorage.getItem('authToken');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 绑定事件监听器
    document.getElementById('loginBtn').addEventListener('click', () => showModal('loginModal'));
    document.getElementById('registerBtn').addEventListener('click', () => showModal('registerModal'));
    document.getElementById('logoutBtn').addEventListener('click', logout);
    document.getElementById('publishBtn').addEventListener('click', publishPost);
    document.getElementById('rechargeBtn').addEventListener('click', () => showModal('rechargeModal'));
    
    // 表单提交事件
    document.getElementById('loginForm').addEventListener('submit', handleLogin);
    document.getElementById('registerForm').addEventListener('submit', handleRegister);
    document.getElementById('rechargeForm').addEventListener('submit', handleRecharge);
    
    // 检查登录状态
    checkAuthStatus();
}

// 显示模态框
function showModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('hidden');
    modal.classList.add('modal-enter');
}

// 关闭模态框
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.add('hidden');
    modal.classList.remove('modal-enter');
}

// 检查认证状态
async function checkAuthStatus() {
    if (authToken) {
        try {
            const response = await axios.get(`${API_BASE_URL}/auth/me`, {
                headers: { 'Authorization': `Bearer ${authToken}` }
            });
            currentUser = response.data.user;
            updateUIForLoggedInUser();
            loadPosts();
        } catch (error) {
            console.error('认证失败:', error);
            logout();
        }
    }
}

// 更新登录后的UI
function updateUIForLoggedInUser() {
    if (currentUser) {
        document.getElementById('loginBtn').classList.add('hidden');
        document.getElementById('registerBtn').classList.add('hidden');
        document.getElementById('logoutBtn').classList.remove('hidden');
        document.getElementById('userInfo').classList.remove('hidden');
        document.getElementById('postArea').classList.remove('hidden');
        
        document.getElementById('usernameDisplay').textContent = currentUser.username;
        document.getElementById('userIdDisplay').textContent = currentUser.id;
        document.getElementById('balanceDisplay').textContent = currentUser.balance.toFixed(2);
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    
    try {
        const response = await axios.post(`${API_BASE_URL}/auth/login`, {
            username, password
        });
        
        authToken = response.data.token;
        currentUser = response.data.user;
        localStorage.setItem('authToken', authToken);
        
        updateUIForLoggedInUser();
        closeModal('loginModal');
        loadPosts();
        
        showMessage('登录成功！', 'success');
    } catch (error) {
        showMessage(error.response?.data?.message || '登录失败', 'error');
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    if (password !== confirmPassword) {
        showMessage('两次输入的密码不一致', 'error');
        return;
    }
    
    try {
        const response = await axios.post(`${API_BASE_URL}/auth/register`, {
            username, password
        });
        
        authToken = response.data.token;
        currentUser = response.data.user;
        localStorage.setItem('authToken', authToken);
        
        updateUIForLoggedInUser();
        closeModal('registerModal');
        loadPosts();
        
        showMessage('注册成功！', 'success');
    } catch (error) {
        showMessage(error.response?.data?.message || '注册失败', 'error');
    }
}

// 退出登录
function logout() {
    localStorage.removeItem('authToken');
    authToken = null;
    currentUser = null;
    
    document.getElementById('loginBtn').classList.remove('hidden');
    document.getElementById('registerBtn').classList.remove('hidden');
    document.getElementById('logoutBtn').classList.add('hidden');
    document.getElementById('userInfo').classList.add('hidden');
    document.getElementById('postArea').classList.add('hidden');
    
    document.getElementById('contentList').innerHTML = '';
    
    showMessage('已退出登录', 'info');
}

// 发布动态
async function publishPost() {
    const content = document.getElementById('postContent').value.trim();
    
    if (!content) {
        showMessage('请输入内容', 'error');
        return;
    }
    
    try {
        const response = await axios.post(`${API_BASE_URL}/posts`, {
            content
        }, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        document.getElementById('postContent').value = '';
        loadPosts();
        showMessage('发布成功！', 'success');
    } catch (error) {
        showMessage(error.response?.data?.message || '发布失败', 'error');
    }
}

// 加载动态列表
async function loadPosts() {
    try {
        const response = await axios.get(`${API_BASE_URL}/posts`);
        const posts = response.data.posts;
        
        const contentList = document.getElementById('contentList');
        contentList.innerHTML = '';
        
        posts.forEach(post => {
            const postElement = createPostElement(post);
            contentList.appendChild(postElement);
        });
    } catch (error) {
        console.error('加载动态失败:', error);
    }
}

// 创建动态元素
function createPostElement(post) {
    const div = document.createElement('div');
    div.className = 'bg-white rounded-lg shadow p-6 post-card';
    
    div.innerHTML = `
        <div class="flex items-center mb-4">
            <div class="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
                ${post.username.charAt(0).toUpperCase()}
            </div>
            <div class="ml-3">
                <h4 class="font-semibold">${post.username}</h4>
                <p class="text-sm text-gray-500">${formatDate(post.created_at)}</p>
            </div>
        </div>
        <div class="post-content mb-4">
            ${escapeHtml(post.content)}
        </div>
        <div class="flex items-center space-x-4 text-gray-500">
            <button class="hover:text-blue-600 like-btn" data-post-id="${post.id}">
                <i class="far fa-heart"></i> ${post.likes || 0}
            </button>
            <button class="hover:text-blue-600 comment-btn" data-post-id="${post.id}">
                <i class="far fa-comment"></i> ${post.comments || 0}
            </button>
        </div>
    `;
    
    return div;
}

// 处理充值
async function handleRecharge(e) {
    e.preventDefault();
    
    const amount = document.getElementById('rechargeAmount').value;
    const paymentMethod = document.getElementById('paymentMethod').value;
    
    try {
        const response = await axios.post(`${API_BASE_URL}/payments/recharge`, {
            amount: parseFloat(amount),
            payment_method: paymentMethod
        }, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        // 模拟支付成功
        setTimeout(() => {
            updateUserBalance(parseFloat(amount));
            closeModal('rechargeModal');
            showMessage(`充值成功！获得 ¥${amount}`, 'success');
        }, 1000);
        
    } catch (error) {
        showMessage(error.response?.data?.message || '充值失败', 'error');
    }
}

// 更新用户余额
async function updateUserBalance(amount) {
    try {
        const response = await axios.get(`${API_BASE_URL}/auth/me`, {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        currentUser = response.data.user;
        document.getElementById('balanceDisplay').textContent = currentUser.balance.toFixed(2);
    } catch (error) {
        console.error('更新余额失败:', error);
    }
}

// 工具函数
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showMessage(message, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `${type}-message`;
    messageDiv.textContent = message;
    
    const container = document.querySelector('.max-w-7xl');
    container.insertBefore(messageDiv, container.firstChild);
    
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}

// 点击模态框外部关闭
window.addEventListener('click', function(e) {
    if (e.target.classList.contains('fixed') && e.target.classList.contains('inset-0')) {
        e.target.classList.add('hidden');
    }
});
